from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse, HTMLResponse
from sqlalchemy.ext.asyncio import AsyncSession
import uvicorn
import os
import pathlib
from contextlib import asynccontextmanager
from datetime import datetime

from database.connection import init_db, get_session
from admin.admin import create_admin
from services.shopify_service import shopify_service
from services.report_service import ReportService
from services.scheduler_service import scheduler_service, startup_event, shutdown_event
from services.sync_service import sync_service
from api import users, products, orders, production
# 暂时注释掉 reports 导入，确保应用能启动
# from api.routes import reports


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时初始化数据库
    await init_db()
    print("数据库初始化完成")
    
    # 启动定时任务调度器
    startup_event()
    print("定时任务调度器启动完成")
    
    # 启动Shopify同步服务（异步执行）
    import asyncio
    asyncio.create_task(sync_service.start_scheduled_sync())
    print("Shopify同步服务已启动")
    
    # 已禁用初始同步，避免自动创建测试数据
    # print("执行初始同步...")
    # asyncio.create_task(sync_service.sync_all_data())
    # print("初始同步已触发")
    
    yield
    
    # 关闭时清理资源
    scheduler_service.stop()
    print("定时任务调度器已停止")
    
    # 停止同步服务
    await sync_service.stop_scheduled_sync()
    print("Shopify同步服务已停止")
    
    shopify_service.close_session()
    print("应用关闭")


# 创建FastAPI应用
app = FastAPI(
    title="3D定制商品生产平台",
    description="基于FastAPI + SQLModel + SQLAdmin的3D定制商品生产平台",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该配置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建上传目录
UPLOAD_DIR = "uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(f"{UPLOAD_DIR}/images", exist_ok=True)
os.makedirs(f"{UPLOAD_DIR}/models", exist_ok=True)
os.makedirs(f"{UPLOAD_DIR}/production", exist_ok=True)

# 创建导出目录
EXPORT_DIR = "exports"
os.makedirs(EXPORT_DIR, exist_ok=True)

# 挂载静态文件
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
app.mount("/exports", StaticFiles(directory=EXPORT_DIR), name="exports")
app.mount("/static", StaticFiles(directory="static"), name="static")

# 报表页面路由
@app.get("/reports", response_class=HTMLResponse)
async def reports_page():
    """报表展示页面"""
    try:
        reports_html_path = pathlib.Path(__file__).parent / "static" / "reports.html"
        with open(reports_html_path, "r", encoding="utf-8") as f:
            return HTMLResponse(content=f.read())
    except FileNotFoundError:
        return HTMLResponse(content="报表页面文件不存在", status_code=404)
    except Exception as e:
        return HTMLResponse(content=f"加载报表页面失败: {str(e)}", status_code=500)

# 创建管理员界面
admin = create_admin(app)

# 注册API路由
app.include_router(users.router, prefix="/api/users", tags=["users"])
app.include_router(products.router, prefix="/api/products", tags=["products"])
app.include_router(orders.router, prefix="/api/orders", tags=["orders"])
app.include_router(production.router, prefix="/api/production", tags=["production"])
# 暂时注释掉 reports 路由，确保应用能启动
# app.include_router(reports.router, prefix="/api/reports", tags=["reports"])


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "欢迎使用3D定制商品生产平台API",
        "version": "1.0.0",
        "docs": "/docs",
        "admin": "/admin"
    }


@app.get("/api/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "shopify_sync_status": scheduler_service.get_status() if 'scheduler_service' in globals() else {}
    }


@app.get("/api/sync-status")
async def get_sync_status(session: AsyncSession = Depends(get_session)):
    """获取同步状态信息"""
    try:
        # 获取数据库中的同步状态
        from database.models import Product, Order, ShopifySyncLog
        from sqlmodel import select
        
        # 检查带Shopify ID的商品数量
        result = await session.execute(
            select(Product).where(Product.shopify_product_id.isnot(None))
        )
        shopify_products = result.scalars().all()
        
        # 检查带Shopify ID的订单数量
        result = await session.execute(
            select(Order).where(Order.shopify_order_id.isnot(None))
        )
        shopify_orders = result.scalars().all()
        
        # 检查最近的同步日志
        result = await session.execute(
            select(ShopifySyncLog).order_by(ShopifySyncLog.created_at.desc()).limit(5)
        )
        recent_logs = result.scalars().all()
        
        # 获取最后一次同步时间
        last_sync = None
        if recent_logs:
            last_sync = recent_logs[0].created_at.isoformat()
        
        status_data = {
            "success": True,
            "data": {
                "shopify_enabled": shopify_service.enabled,
                "sync_service_running": sync_service.running,
                "shopify_products_count": len(shopify_products),
                "shopify_orders_count": len(shopify_orders),
                "last_sync_time": last_sync,
                "sync_logs": [
                    {
                        "id": log.id,
                        "resource_type": log.shopify_resource_type,
                        "sync_status": log.sync_status,
                        "created_at": log.created_at.isoformat(),
                        "error_message": log.error_message
                    }
                    for log in recent_logs
                ]
            }
        }
        
        return JSONResponse(content=status_data)
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取同步状态失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/dashboard")
async def get_dashboard_stats(session: AsyncSession = Depends(get_session)):
    """获取仪表板统计数据"""
    try:
        report_service = ReportService(session)
        stats = await report_service.get_dashboard_stats()
        return JSONResponse(content={"success": True, "data": stats})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取统计数据失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/orders")
async def get_order_stats(session: AsyncSession = Depends(get_session)):
    """获取订单统计"""
    try:
        report_service = ReportService(session)
        stats = await report_service.get_order_stats_by_status()
        return JSONResponse(content={"success": True, "data": stats})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取订单统计失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/revenue")
async def get_revenue_stats(days: int = 30, session: AsyncSession = Depends(get_session)):
    """获取收入统计"""
    try:
        report_service = ReportService(session)
        stats = await report_service.get_revenue_stats(days)
        return JSONResponse(content={"success": True, "data": stats})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取收入统计失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/products")
async def get_product_stats(session: AsyncSession = Depends(get_session)):
    """获取商品统计"""
    try:
        report_service = ReportService(session)
        stats = await report_service.get_product_stats()
        return JSONResponse(content={"success": True, "data": stats})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取商品统计失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/users")
async def get_user_stats(session: AsyncSession = Depends(get_session)):
    """获取用户统计"""
    try:
        report_service = ReportService(session)
        stats = await report_service.get_user_stats()
        return JSONResponse(content={"success": True, "data": stats})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取用户统计失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/production")
async def get_production_stats(session: AsyncSession = Depends(get_session)):
    """获取生产统计"""
    try:
        report_service = ReportService(session)
        stats = await report_service.get_production_stats()
        return JSONResponse(content={"success": True, "data": stats})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取生产统计失败: {str(e)}"},
            status_code=500
        )


@app.get("/api/stats/monthly-report")
async def get_monthly_report(year: int, month: int, session: AsyncSession = Depends(get_session)):
    """获取月度报告"""
    try:
        report_service = ReportService(session)
        report = await report_service.get_monthly_report(year, month)
        return JSONResponse(content={"success": True, "data": report})
    except Exception as e:
        return JSONResponse(
            content={"success": False, "message": f"获取月度报告失败: {str(e)}"},
            status_code=500
        )


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )